'''
Created on Jul 9, 2011

@author: kafkef
'''

       
from PyQt4.QtGui import *
from PyQt4.QtCore import (QObject, SIGNAL, QAbstractTableModel, Qt, QModelIndex,
                          QVariant)

from dexen.system.client import ui
from dexen.system.client.proxy import JobProxy
from dexen.system.common.base import Action
from dexen.system.client.ui.pages.base_job_page import BaseJobTableModel,\
    BaseJobPage


svr_proxy = ui.svr_proxy


class JobAdvanceModel(BaseJobTableModel):
    def __init__(self, header_items, advance_items, advance_log, parent=None):
        BaseJobTableModel.__init__(self, header_items, advance_items, 
                                   advance_log, parent)


class JobAdvancePage(BaseJobPage):       
    def __init__(self):
        BaseJobPage.__init__(self)
#        self._create_widgets()
#        self._models = {} #job_id: JobAdvancementModel
#        self._cur_job_id = None
    
    # Override the base class method
    def on_refresh(self):
        if self._cur_job_id is None: return
        print "JobAdvancePage::on_refresh()"
        job_id = self._cur_job_id
        job_proxy = svr_proxy.get_job_cached(job_id)
        assert isinstance(job_proxy, JobProxy)
        step_size = self._step_size_spinbox.value()
        advance_log = job_proxy.get_advancement_log(step_size)
        
        # Tokenize the advancement log
        items = advance_log.split("\n")
        header_items = items[0].split(",")
        advance_items = []
        for item in items[1:]:
            items = item[:-1].split(",")
            # Filter out the possible empty lines at the end of the file
            if len(items) > 1:
                advance_items.append(items)
        print len(advance_items), "are received."
        model = JobAdvanceModel(header_items, advance_items, advance_log)               
        # Save the fresh model
        self._models[job_id] = model 
        # Update the view based on the fresh model
        self._table_view.setModel(model)
        self._table_view.resizeColumnsToContents()

        
